package com.framework.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.framework.dao.BankDao;
import com.framework.entity.sys.SysAgent;
import com.framework.entity.sys.SysBank;
import com.framework.entity.sys.SysPayment;
import com.framework.exception.RRException;
import com.framework.exception.menu.RespCode;
import com.framework.page.PageUtils;
import com.framework.redis.util.RedisUtil;
import com.framework.service.*;
import com.framework.utils.bank.BankUtil;
import com.framework.utils.string.StringUtil;
import com.framework.validator.Assert;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("bankService")
public class BankServiceImpl extends ServiceImpl<BankDao, SysBank> implements BankService {

    @Autowired
    private AgentService agentService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private DeptSmsService deptSmsService;

    @Override
    public List<SysBank> queryBankList(String token) {
        Assert.isNull(token, "参数错误");
        SysAgent agent = agentService.queryAgentByToken(token);
        return baseMapper.queryBankList(agent.getAgentId());
    }

    @Override
    public void insertBank(SysBank bank, String vCode, String token) {
        Assert.isNull(bank, "参数错误");
        if (StringUtils.isBlank(bank.getBankNo()) ||
                StringUtils.isBlank(bank.getCardName()) ||
                StringUtils.isBlank(bank.getPhone()) ||
                StringUtils.isBlank(vCode) ||
                StringUtils.isBlank(token) ||
                bank.getIsDefault() == null ||
                bank.getIsDefault() == 0
        ) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = agentService.queryAgentByToken(token);
        Long deptId = agent.getDeptId();
        SysBank bankInfo = selectBankByNo(bank.getBankNo(), deptId);
        if (bankInfo != null) {
            throw new RRException("9000", "此卡号已经存在");
        }
        deptSmsService.checkSms("i_bank", bank.getPhone(), vCode);
        //查询所属的支付信息,是否需要银行行号
        SysPayment payment = paymentService.queryPaymentByDeptId(deptId);
        if (payment == null) {
            throw new RRException("9000", "未查询到签约的代付配置信息");
        }
        //类型为2是需要录入银行行号
        Integer payType = payment.getPayType();
        if (payType.intValue() == 2) {
            String lineNo = bank.getLineNo();
            Assert.isBlank(lineNo, "银行行号必填");
        }
        bank.setCreateDate(new Date());
        //查询银行的信息
        Map<String, Object> bankMap = BankUtil.getBankCodeAndName(bank.getBankNo());
        String bankCode = (String) bankMap.get("bankCode");
        String bankName = (String) bankMap.get("bankName");
        bank.setBankCode(bankCode);
        bank.setBankName(bankName);
        bank.setAgentId(agent.getAgentId());
        bank.setDeptId(deptId);
        baseMapper.insert(bank);
        //清除缓存
        redisUtil.del("i_bank_" + bank.getPhone());
        //查询是否添加成功
        SysBank sysBankInfo = selectBankByNo(bank.getBankNo(), deptId);
        if (sysBankInfo == null) {
            throw new RRException("9000", "银行卡信息添加失败");
        }
        //设置成默认
        if (bank.getIsDefault() == 1) {
            setDefault(sysBankInfo.getBankId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateBank(SysBank bank, String vCode, String token) {
        Assert.isNull(bank, "参数错误");
        if (StringUtils.isBlank(bank.getBankNo()) ||
                StringUtils.isBlank(bank.getCardName()) ||
                StringUtils.isBlank(bank.getPhone()) ||
                StringUtils.isBlank(vCode) ||
                StringUtils.isBlank(token) ||
                bank.getBankId() == null ||
                bank.getBankId() == 0 ||
                bank.getIsDefault() == null ||
                bank.getIsDefault() == 0
        ) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysAgent agent = agentService.queryAgentByToken(token);
        Long deptId = agent.getDeptId();
        //对银行卡号校验是否存在
        SysBank sysBank = infoBank(token, bank.getBankId());
        String bankNo = sysBank.getBankNo();
        if (!StringUtils.equals(bankNo, bank.getBankNo())) {
            SysBank bankInfo = selectBankByNo(bank.getBankNo(), deptId);
            if (bankInfo != null) {
                throw new RRException("9000", "此卡号已经存在");
            }
        }
        deptSmsService.checkSms("u_bank", bank.getPhone(), vCode);
        //查询所属的支付信息,是否需要银行行号
        SysPayment payment = paymentService.queryPaymentByDeptId(deptId);
        if (payment == null) {
            throw new RRException("9000", "未查询到签约的·提现信息");
        }
        Integer payType = payment.getPayType();//类型为2是需要录入银行行号
        if (payType.intValue() == 2) {
            String lineNo = bank.getLineNo();
            Assert.isBlank(lineNo, "银行行号必填");
        }
        baseMapper.updateBankById(bank);
        //清除缓存
        redisUtil.del("u_bank_" + bank.getPhone());
        //设置成默认
        if (bank.getIsDefault() == 1) {
            setDefault(bank.getBankId());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysBank infoBank(String token, Long bankId) {
        SysAgent agent = agentService.queryAgentByToken(token);
        SysBank bank = new SysBank();
        bank.setBankId(bankId);
        SysBank sysBank = baseMapper.selectOne(bank);
        Assert.isNull(sysBank, "未查询到银行卡信息");
        if (sysBank.getAgentId().intValue() != agent.getAgentId().intValue()) {
            throw new RRException("9000", "此银行卡不属于当前登录人");
        }
        return sysBank;
    }

    @Override
    public SysBank selectBankByNo(String bankNo, Long deptId) {
        SysBank bank = new SysBank();
        bank.setBankNo(bankNo);
        bank.setDeptId(deptId);
        bank.setIsShow(1);
        SysBank sysBank = baseMapper.selectOne(bank);
        return sysBank;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setDefault(Long bankId) {
        SysBank bank = new SysBank();
        bank.setBankId(bankId);
        SysBank sysBank = baseMapper.selectOne(bank);
        if (sysBank != null) {
            Long agentId = sysBank.getAgentId();
            baseMapper.updateDefaultByAgentId(agentId);
            baseMapper.isDefaultById(bankId);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delBank(Long bankId) {
        if (bankId == null ||
                bankId == 0) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        baseMapper.delBank(bankId);
    }

    @Override
    public SysBank queryDefault(Long agentId) {
        if (agentId == null ||
                agentId == 0) {
            throw new RRException(RespCode.NOT_PARAM_ERROR);
        }
        SysBank bank = baseMapper.queryDefault(agentId);
        if (bank == null) {
            bank = queryBankAndSetDefault(agentId);
        }
        return bank;
    }

    private SysBank queryBankAndSetDefault(Long agentId) {

        List<SysBank> banks = selectList(new EntityWrapper<SysBank>()
                .eq("agent_id", agentId)
                .eq("is_show", 1));
        if (banks == null || banks.size() == 0) {
            throw new RRException("9000", "未查询到可用银行卡,请添加银行卡");
        }
        setDefault(banks.get(0).getBankId());
        return banks.get(0);
    }

    @Override
    public PageUtils queryBankCardList(Map<String, Object> params) {
        Integer pageSize = Integer.valueOf(params.get("limit").toString());
        Integer currPage = Integer.valueOf(params.get("page").toString());
        params.put("start", (currPage - 1) * pageSize);
        params.put("limit", pageSize);
        List<Map<String, Object>> list = baseMapper.queryBankCardList(params);
        Integer totalCount = baseMapper.queryBankCardCount(params);
        return new PageUtils(list, totalCount, pageSize, currPage);
    }

    @Override
    public SysBank queryById(Long bankId) {
        return baseMapper.selectById(bankId);
    }

    @Override
    public void addBankByVerify(String bankNo, SysAgent agent) {
        bankNo=Assert.hasSpace(bankNo);
        //查询银行的信息
        Map<String, Object> bankMap = BankUtil.getBankCodeAndName(bankNo);
        String bankCode = (String) bankMap.get("bankCode");
        String bankName = (String) bankMap.get("bankName");
        bankName = StringUtil.isEmpty(bankName) ? "其他银行" : bankName;
        //添加银行卡信息
        SysBank bank = queryBankByAgentId(agent.getAgentId());
        if(bank==null){
            bank=new SysBank();
            bank.setCreateDate(new Date());
            bank.setPhone(agent.getPhone());
            bank.setCreateDate(new Date());
            bank.setCardName(agent.getName());
            bank.setIsDefault(1);
            bank.setBankCode(bankCode);
            bank.setBankNo(bankNo);
            bank.setBankName(bankName);
            bank.setAgentId(agent.getAgentId());
            bank.setDeptId(agent.getDeptId());
            bank.setIsShow(1);
            insert(bank);
        }else {
            bank.setPhone(agent.getPhone());
            bank.setCreateDate(new Date());
            bank.setCardName(agent.getName());
            bank.setIsDefault(1);
            bank.setBankCode(bankCode);
            bank.setBankNo(bankNo);
            bank.setBankName(bankName);
            bank.setAgentId(agent.getAgentId());
            bank.setDeptId(agent.getDeptId());
            bank.setIsShow(1);
            updateById(bank);

        }
    }

    @Override
    public SysBank queryBankByAgentId(Long agentId) {
        return selectOne(new EntityWrapper<SysBank>().eq("agent_id",agentId));
    }

    @Override
    public SysBank addBankByVerify(String bankNo, SysAgent agent, String phone) {
        bankNo=Assert.hasSpace(bankNo);
        //查询银行的信息
        Map<String, Object> bankMap = BankUtil.getBankCodeAndName(bankNo);
        String bankCode = (String) bankMap.get("bankCode");
        String bankName = (String) bankMap.get("bankName");
        bankName = StringUtil.isEmpty(bankName) ? "其他银行" : bankName;
        //添加银行卡信息
        SysBank bank = queryBankByAgentId(agent.getAgentId());
        if(bank==null){
            bank=new SysBank();
            bank.setCreateDate(new Date());
            bank.setPhone(phone);
            bank.setCreateDate(new Date());
            bank.setCardName(agent.getName());
            bank.setIsDefault(1);
            bank.setBankCode(bankCode);
            bank.setBankNo(bankNo);
            bank.setBankName(bankName);
            bank.setAgentId(agent.getAgentId());
            bank.setDeptId(agent.getDeptId());
            bank.setIsShow(1);
            bank.setIsReserved(2);
            bank.setReservedBankNo(bankNo);
            insert(bank);
        }else {
            bank.setPhone(phone);
            bank.setCreateDate(new Date());
            bank.setCardName(agent.getName());
            bank.setIsDefault(1);
            bank.setBankCode(bankCode);
            bank.setBankNo(bankNo);
            bank.setBankName(bankName);
            bank.setAgentId(agent.getAgentId());
            bank.setDeptId(agent.getDeptId());
            bank.setIsShow(1);
            bank.setIsReserved(2);
            bank.setReservedBankNo(bankNo);
            updateById(bank);
        }

        return bank;

    }


}
